<template>
  <div class="w-260 h-130 relative">
    <div
      v-if="showBg"
      class="z-1 absolute left-0 top-0 flex h-full w-full items-center justify-center"
    >
      暂无数据
    </div>
    <div :id="id" class="relative z-10 h-full w-full"></div>
  </div>
</template>

<script setup lang="tsx">
import { onMounted, reactive, ref, toRaw, useId } from 'vue';
import { realDataChart } from '@/utils';
import { useEventSource } from '@boeyo/hooks';
import { useUserStore } from '@boeyo/portal';

interface Props {
  stationId: string;
}

const props = defineProps<Props>();
const channels = reactive([
  {
    name: 'EIZ',
    des: '竖桥向',
    color: '#F16995',
  },
  {
    name: 'EIN',
    des: '横桥向',
    color: '#77E3F9',
  },
  {
    name: 'EIE',
    des: '纵桥向',
    color: '#DFC428',
  },
]);
const id = useId();
const userStore = useUserStore();

let renderChart;
const showBg = ref(true);

const init = () => {
  const { renderChart: _renderChart } = realDataChart({
    target: document.getElementById(id),
    title: false,
    direction: 'vertical',
    channels: toRaw(channels),
  });
  renderChart = _renderChart;
};

onMounted(() => {
  init();
});

const formatData = (cb) => {
  let data = {};
  const checkData = () => {
    let flag = false;
    if (Object.keys(data).length !== 3) return false;
    Object.values(data)
      .map((item) => item[0][0])
      .reduce((prev, cur) => {
        flag = prev === cur;
        return cur;
      });
    return flag;
  };
  const push = (_data) => {
    Object.keys(_data).forEach((_key) => {
      let key;
      switch (_key) {
        case 'Z':
          key = 'EIZ';
          break;
        case 'N':
          key = 'EIN';
          break;
        case 'E':
          key = 'EIE';
          break;
        default:
          break;
      }
      if (_key !== 'X') {
        data[key] = _data[_key];
      }
    });
    if (checkData()) {
      cb(data);
      data = {};
    }
  };
  return push;
};

const push = formatData((data) => {
  const dataSource = {};
  for (const key in data) {
    if (Object.prototype.hasOwnProperty.call(data, key)) {
      const element = data[key];

      dataSource[key] = element.reduce((prev, cur) => {
        if (cur[0] % 100 === 0) {
          cur[1] = cur[1] / 500;

          prev.push(cur);
        }

        return prev;
      }, []);
    }
  }
  if (Object.keys(dataSource).length) {
    showBg.value = false;
  }

  renderChart(dataSource);
});

const random = Math.random().toString().slice(-6);
const { connect, disconnect } = useEventSource(
  `/api/edge/sse/300/${random}/${props.stationId}`,
  {
    headers: {
      ['Authorization']: `Bearer ${userStore.token}`,
      'Content-Type': 'application/json',
      Accept: '*/*',
    },
    withCredentials: false,
    onMessage(res) {
      const data = JSON.parse(res);
      push(data);
    },
    onError(error) {
      console.log(error);
      disconnect();
    },
  },
);

onMounted(() => {
  connect();
});
</script>
